import React, { useRef, useState } from 'react'
// eslint-disable-next-line import/no-extraneous-dependencies
import { UploadOutlined } from '@ant-design/icons'
import {
  Button,
  Card,
  Empty,
  Input,
  message,
  Modal,
  notification,
  Space
} from 'antd'
import {
  ipcRendererInvoke,
  ipcRendererOn,
  ipcRendererSend
} from '@common/desktopUtils'
import type { NotificationArgsProps } from 'antd'

type NotificationPlacement = NotificationArgsProps['placement']

let uploadList: any[] = []

function UploadFile() {
  const [messageApi, contextHolder] = message.useMessage()
  const [api, ncontextHolder] = notification.useNotification()
  const [submitValue, setSubmitValue] = useState({
    advertiser_id: '1825534183839754',
    videoFiles: []
  })
  const [uploadData, setUploadData] = useState<Record<string, any>[]>([])
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isCanSubmit, setIsCanSubmit] = useState(false)
  const rfPath = useRef<any[]>([])
  const showModal = () => {
    setIsModalOpen(true)
  }

  const handleClose = () => {
    setIsModalOpen(false)
  }

  const handleBlur = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSubmitValue({
      ...submitValue,
      advertiser_id: e.target.value
    })
  }
  const openNotification = (placement: NotificationPlacement, key: string) => {
    api.info({
      key,
      message: '上传提示',
      description: (
        <b style={{ color: 'red' }}>视频正在上传中请勿操作界面避免操作失败</b>
      ),
      placement
    })
  }
  const destroyNotification = (key: string) => {
    api.destroy(key)
  }
  // eslint-disable-next-line consistent-return
  const uploadVideoFile = (): any => {
    const { advertiser_id, videoFiles } = submitValue
    const queryPath = rfPath.current?.length > 0 ? rfPath.current : videoFiles
    uploadList = []
    if (!advertiser_id) {
      return messageApi.open({
        type: 'error',
        content: '请输入广告主ID'
      })
    }
    if (queryPath.length === 0) {
      return messageApi.open({
        type: 'error',
        content: '请选择至少一个视频文件'
      })
    } else {
      openNotification('bottomRight', 'open')
      setIsCanSubmit(true)
      const tasks = queryPath.map((videoFile: any) => {
        return ipcRendererInvoke('send-video', {
          advertiser_id,
          video_file: videoFile.path,
          filename: videoFile.name
        }) // 保留索引以维持顺序
      })
      ipcRendererOn('video-result', async (_, result: Record<string, any>) => {
        uploadList.push(result)
        const { videoPath } = result
        setUploadData(uploadList)
        if (uploadList.length === tasks.length) {
          destroyNotification('open')
          setIsCanSubmit(false)
          rfPath.current = videoPath
          const len = uploadList.filter((item) => item.code !== 0).length
          if (len !== 0) {
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment,no-void
            await messageApi.open({
              type: 'info',
              content: `上传失败${len}个视频文件`
            })
            showModal()
          } else {
            ipcRendererSend('clear-video')
            setSubmitValue({
              videoFiles: [],
              advertiser_id: ''
            })
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment,no-void
            await messageApi.open({
              type: 'success',
              content: `恭喜你，${tasks.length}个视频全部上传成功`
            })
          }
        }
      })
    }
  }
  const handleGetVideo = () => {
    ipcRendererSend('clear-video')
    ipcRendererSend('open-dialog')
    ipcRendererOn('dialog-result', (_, data) => {
      setSubmitValue({
        ...submitValue,
        videoFiles: (data as []) || []
      })
    })
  }

  return (
    <div>
      {contextHolder}
      {ncontextHolder}
      <Space direction="vertical">
        <Input
          addonBefore="广告主ID"
          value={submitValue.advertiser_id}
          onChange={handleBlur}
        />
        <Button
          shape="round"
          icon={<UploadOutlined />}
          onClick={handleGetVideo}
        >
          选择上传的文件
        </Button>
        <Button type="primary" onClick={uploadVideoFile} disabled={isCanSubmit}>
          提交
        </Button>
      </Space>
      <div>
        <Space size={16} style={{ marginTop: 20 }}>
          <Card title="已选择的视频" style={{ minWidth: 400 }}>
            {submitValue?.videoFiles.length ? (
              submitValue?.videoFiles.map(
                (item: Record<string, any>, index) => {
                  // eslint-disable-next-line react/no-array-index-key
                  return <p key={`${item.name}-${index}`}>{item.name}</p>
                }
              )
            ) : (
              <Empty />
            )}
          </Card>
          <Card
            title="上传消息"
            extra={
              <Button
                onClick={() => {
                  setUploadData([])
                }}
              >
                清空视频消息
              </Button>
            }
            style={{ minWidth: 400 }}
          >
            {uploadData?.length ? (
              uploadData.map((item: Record<string, any>) => {
                return (
                  <p
                    key={`${item.name}`}
                    style={{ color: item.code === 0 ? 'seagreen' : 'red' }}
                  >
                    {item.filename}
                    {item.code === 0 ? '' : `（失败原因：${item.message}）`}
                  </p>
                )
              })
            ) : (
              <Empty />
            )}
          </Card>
        </Space>
      </div>
      <Modal
        title="提示"
        open={isModalOpen}
        onOk={uploadVideoFile}
        onCancel={handleClose}
        cancelText="我知道了"
        okText="重新上传失败视频"
      >
        <div>
          上传失败{uploadData.filter((item) => item.code !== 0).length}
          个视频文件
        </div>
      </Modal>
    </div>
  )
}
export default UploadFile
